package graph

type Vector string

type MakeGraph struct {
	Vector []Vector
	B      map[int][2]int
}

type MGraph struct {
	vexs        []Vector
	arc         [100][100]int
	NumVertexes int
	NumEdges    int
}

//根据给定数组添加

func CreateMGraph(graph *MakeGraph) *MGraph {
	g := new(MGraph)

	g.vexs = graph.Vector
	g.NumVertexes = len(g.vexs)
	g.NumEdges = len(graph.B)

	for vi, vj := range graph.B {

		if !(vi < len(g.vexs) && vj[0] < len(g.vexs)) {
			panic("MakeGraph err vi or vj is nil")
		}

		g.arc[vi][vj[0]] = vj[1]
		//对称
		g.arc[vj[0]][vi] = vj[1]
	}

	return g

}

func (m *MGraph) LocateVex(v Vector) int {
	i := 0
	for ; i < m.NumVertexes; i++ {
		if m.vexs[i] == v {
			return i
		}
	}

	return -1
}

func (m *MGraph) GetVex(i int) (Vector, error) {
	if i >= m.NumVertexes {
		return "", IndexErr
	}

	return m.vexs[i], nil

}

func (m *MGraph) PutVex(i int, value Vector) error {
	if i >= m.NumVertexes {
		return IndexErr
	}

	m.vexs[i] = value

	return nil
}

func (m *MGraph) FirstAdjVex(v int) int {
	for j := 0; j < m.NumVertexes; j++ {
		if m.arc[v][j] > 0 {
			return j
		}
	}

	return -1
}

func (m *MGraph) NextAdjVex(v int, w int) int {
	for j := w + 1; j < m.NumVertexes; j++ {
		if m.arc[v][j] > 0 {
			return j
		}
	}

	return -1
}

func (m *MGraph) InsertVex(vector Vector) error {

	if m.NumVertexes >= 99 {
		return VectorMaxErr
	}

	m.vexs = append(m.vexs, vector)
	m.NumVertexes++

	return nil

}

func (m *MGraph) InsertArc(v Vector, w Vector, q int) error {
	vi := m.LocateVex(v)
	wi := m.LocateVex(w)

	if vi == -1 || wi == -1 {
		return VectorIsNilErr
	}

	m.arc[vi][wi] = q
	m.arc[wi][vi] = q

	return nil

}
